package pl.koziolekweb.szkola.JUWatkiBad;

// JU-WatkiBad/WatkiBad.java
 
public class WatkiBad extends Thread {

    long number = 0L;

    public static void main(String[] args) {
        new WatkiBad().start();
    }

    WatkiBad() {
        int ILE = 20;
        for (int i = 0; i < ILE; ++i)
            new Thread(new Watek(this),""+i).start();
        System.out.println("Wszystkie watki wystartowane");
    }

    long getNumber() {
        if (number < 1) number = number + 1;
        number = number - 1;
        return number;
    }

    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) { }
        System.out.println("Killing program");
        System.out.println("Number jest " + number);
        System.exit(0);
    }
}

class Watek implements Runnable {
    WatkiBad w;
    Thread t = null;

    Watek(WatkiBad w) {
        this.w = w;
    }

    public void run() {
        t = Thread.currentThread();
        while (true) {
            long n = w.getNumber();
            if (n != 0) {
                System.out.println("n = " + n +
                           " w watku nr " + t.getName());
                break;
            }
        }
    }
}
